﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DigitalSolutionLibrary.SqlDatabase;
using System.IO;
using System.Xml;
using DigitalSolutionLibrary.Security;
using System.Data;

namespace DigitalSolutionManagement
{
    static class Program
    {
        public static frmMain main;
        public static DatabaseWrapper dbWrapper;
        public static readonly int RowPerPage = 10;
        public static int EmpId;
        public static DataTable dtPermission;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            string appConfigPath = Application.StartupPath + @"\AppConfig.htd";
            if (File.Exists(appConfigPath))
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(appConfigPath);

                dbWrapper = new DatabaseWrapper(xDoc.SelectSingleNode("/AppConfig/ServerName").InnerText,
                    xDoc.SelectSingleNode("/AppConfig/DBName").InnerText,
                    xDoc.SelectSingleNode("/AppConfig/UserName").InnerText,
                    TripleDES.Decryption(xDoc.SelectSingleNode("/AppConfig/Password").InnerText));
                
                frmLogIn frmLogin = new frmLogIn();
                if (frmLogin.ShowDialog() == DialogResult.OK)
                {
                    main = new frmMain();
                    Application.Run(main);
                }
                else
                    Application.Exit();
            }
            else
            {
                Application.Run(new frmDBConfig());
            }
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            frmAppError frm = new frmAppError((Exception)e.ExceptionObject);
            frm.ShowDialog();
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            frmAppError frm = new frmAppError(e.Exception);
            frm.ShowDialog();
        }
    }
}
